package com.sunshine.lnuplusweb.controller;

import com.sunshine.lnuplusweb.entities.WhatToDo2021;
import com.sunshine.lnuplusweb.service.WhatToDo2021Service;
import com.sunshine.lnuplusweb.utils.CryptoUtils;
import com.sunshine.lnuplusweb.utils.Result;
import com.sunshine.lnuplusweb.utils.WebSocket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * 活动控制类
 * 现在的活动有 2021 你想做什么
 */
@Controller
public class ActivityController {

    @Resource
    private WhatToDo2021Service whatToDo2021Service;

    @GetMapping({"what_to_do_2021", "what_to_do_2021.html"})
    public String whatToDo2021(HttpSession httpSession, Model model) {
        //这个
        List<WhatToDo2021> whatToDoList = whatToDo2021Service.getAll();
        model.addAttribute("what_to_do_list", whatToDoList);

        String userId = (String) httpSession.getAttribute("userId");
        if (userId != null) {
            model.addAttribute("login", true);
            model.addAttribute("userId", "欢迎 " + httpSession.getAttribute("userId"));
            //添加数据库中的用户名，用来弹幕比对是否是自己发的信息
            model.addAttribute("userIdDB", CryptoUtils.encrypByMD5((String) httpSession.getAttribute("userId")));
        } else {
            model.addAttribute("login", false);
            model.addAttribute("userIdDB", "");
        }
        return "what_to_do_2021";
    }

    //注意啊，这个需要responseBody
    @PostMapping({"send_danmu"})
    @ResponseBody
    public Result toSaveWhatToDo2021(@RequestParam("content") String content, HttpSession httpSession) {
        //自定义返回实体类并且发送到前端，由前端ajax接受并处理
        Result result = new Result();

        String userId = (String) httpSession.getAttribute("userId");
        if (userId != null) {
            whatToDo2021Service.insert(CryptoUtils.encrypByMD5((String) httpSession.getAttribute("userId")), content);
            try {
                WebSocket.sendDanmu(content);
                result.setResultCode(Result.RESULT_OK);
            } catch (Exception e) {
                e.printStackTrace();
                result.setResultCode(Result.RESULT_SERVICE_ERROR);
            }
        } else {
            result.setResultCode(Result.RESULT_SERVICE_REFUSED);
        }
        return result;
    }
}
